package com.pfzy.lib.sdk.log;

import android.app.ActivityManager;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;
import android.text.TextUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * UXLog目录大小检查器
 */
public class UXLogDirSizeChecker {
    protected static long MAX_LOG_DIR_SIZE = 104857600;// 100Mb
    private static Handler handler = new Handler(Looper.getMainLooper());

    UXLogDirSizeChecker() {}

    public static void checkLogFolderSize(final Context context, final String logDir) {
        if (isMainProcess(context) && !TextUtils.isEmpty(logDir)) {
            new AsyncTask<Void, Void, Void>() {
                @Override
                public Void doInBackground(Void... voids) {
                    try {
                        File logDirFile = new File(logDir);
                        if (logDirFile != null && logDirFile.exists()) {
                            long logDirSize = UXLogDirSizeChecker.getDirSize(logDirFile);
                            if (logDirSize > UXLogDirSizeChecker.MAX_LOG_DIR_SIZE) {
                                UXLogDirSizeChecker.deleteFileByLastModified(logDirFile, logDirSize);
                            }
                        }
                    } catch (Exception e) {
                    }
                    return null;
                }
            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    UXLogDirSizeChecker.checkLogFolderSize(context, logDir);
                }
            }, 10800000L);
        }
    }

    public static long getDirSize(File Folder) {
        long size = 0;
        try {
            File[] fileList = Folder.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    return pathname.isFile() && pathname.getName().endsWith(".xlog");
                }
            });
            for (int i = 0; i < fileList.length; i++) {
                if (fileList[i] != null && !fileList[i].isDirectory()) {
                    size += fileList[i].length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    public static void deleteFileByLastModified(File logDirFile, long totalSize) {
        if (logDirFile != null && logDirFile.exists()) {
            try {
                List<File> fileList = new ArrayList<>(Arrays.asList(logDirFile.listFiles(new FileFilter() {
                    @Override
                    public boolean accept(File pathname) {
                        return pathname.isFile() && pathname.getName().endsWith(".xlog");
                    }
                })));
                Collections.sort(fileList, new Comparator<File>() {
                    @Override
                    public int compare(File o1, File o2) {
                        return o1.lastModified() > o2.lastModified() ? 1 : -1;
                    }
                });
                for (int i = 0; i < fileList.size(); i++) {
                    File file = fileList.get(i);
                    long fileSize = file.length();
                    file.delete();
                    totalSize -= fileSize;
                    if (totalSize < MAX_LOG_DIR_SIZE) {
                        return;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static boolean isMainProcess(Context context) {
        return TextUtils.equals(context.getPackageName(), getCurrentProcessName(context));
    }

    private static String getCurrentProcessName(Context context) {
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> processes = manager.getRunningAppProcesses();
        if (processes != null) {
            int pid = Process.myPid();
            for (ActivityManager.RunningAppProcessInfo processInfo : processes) {
                if (processInfo.pid == pid && !TextUtils.isEmpty(processInfo.processName)) {
                    return processInfo.processName;
                }
            }
        }
        String name = getProcessName(Process.myPid());
        if (TextUtils.isEmpty(name) || !name.contains(context.getPackageName())) {
            return null;
        }
        return name;
    }

    private static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }

            if (reader != null) {
                reader.close();
            }
            return processName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } catch (Throwable th) {
            throw th;
        }
    }
}
